package cn.edu.lingnan.web;

import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.edu.lingnan.dao.CompanyDao;
import cn.edu.lingnan.model.Company;
import cn.edu.lingnan.model.PageBean;
import cn.edu.lingnan.util.DbUtil;
import cn.edu.lingnan.util.JsonUtil;
import cn.edu.lingnan.util.ResponseUtil;
import cn.edu.lingnan.util.StringUtil;

public class CompanySaveServlet extends HttpServlet{
	DbUtil dbUtil=new DbUtil();
	CompanyDao companyDao=new CompanyDao();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String companyName=request.getParameter("companyName");
		String companyDesc=request.getParameter("companyDesc");
		String id=request.getParameter("id");
		Company company=new Company(companyName,companyDesc);
		if(StringUtil.isNotEmpty(id)){
			company.setId(Integer.parseInt(id));
		}
		Connection con=null;
		try{
			con=dbUtil.getCon();
			int saveNums=0;
			JSONObject result=new JSONObject();
			if(StringUtil.isNotEmpty(id)){
				saveNums=companyDao.companyModify(con, company);
			}else{
				saveNums=companyDao.companyAdd(con, company);
			}
			if(saveNums>0){
				result.put("success", "true");
			}else{
				result.put("success", "true");
				result.put("errorMsg", "保存失败");
			}
			ResponseUtil.write(response, result);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				dbUtil.closeCon(con);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
